package model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import test.DBUtil;

public class DiningCarService {
	private DBUtil db;

	public DiningCarService() {
		db = new DBUtil();
	}

	/**
	 * 读取所有用户点餐信息
	 * 
	 * @return
	 */
	public Map<String, List<Map<String, String>>> showAllDc() {
		Map<String, List<Map<String, String>>> dcs = new HashMap<String, List<Map<String, String>>>();
		String sql = "select distinct u.id,u.username from user u join diningcar dc on u.id=dc.userid";
		List<Map<String, String>> users = db.getList(sql);
		for (Map<String, String> m : users) {
			dcs.put(m.get("username"), showDC(m.get("id")));
		}
		return dcs;
	}

	/**
	 * 查找id号
	 * 
	 * @param name
	 * @return
	 */
	public Map<String, String> seekid(String name) {
		String sql = "select id from user where username=?";
		return db.getMap(sql, new String[] { name });
	}

	/**
	 * 从餐车删除
	 * 
	 * @param ids
	 * @return
	 */
	public int delFormDC(String[] ids) {
		int r = 0;
		if (ids != null) {
			String sql = "update food set hits=hits-1 where id=(select foodid from diningcar where id=?)";
			for (String dcid : ids)
				db.update(sql, new String[] { dcid });

			sql = "delete from diningcar where id=?";
			for (String id : ids)
				r += db.update(sql, new String[] { id });
		}
		return r;
	}

	/**
	 * 读取用户点餐信息
	 * 
	 * @param userid
	 * @return
	 */
	public List<Map<String, String>> showDC(String userid) {
		String sql = "SELECT f.*,ft.typename,dc.id as dcid FROM food f JOIN foodtype ft ON f.type=ft.id JOIN diningcar dc ON f.id=dc.foodid WHERE dc.userid=? ORDER BY dcid DESC";
		String[] params = { userid };
		return db.getList(sql, params);
	}

	/**
	 * 添加菜品到点餐车
	 * 
	 * @param userid
	 * @param ids选择多个菜品id
	 * @return添加的数量
	 */
	public int addToDC(String userid, String[] ids) {
		int r = 0;
		if (ids != null) {
			String sql = "insert into diningcar values(null,?,?)";
			for (String foodid : ids) {
				r += db.update(sql, new String[] { userid, foodid });
			}
			// 修改点击次数
			sql = "update food set hits=hits+1 where id=?";
			for (String id : ids) {
				db.update(sql, new String[] { id });
			}
		}
		return r;
	}

}
